import { Table, Button, Input, Select, Popconfirm, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { getCardsList, delCards } from 'api/cards';
import { getDeckList } from '@/api/modules/group';
import { useLocation, useNavigate } from 'react-router-dom';
import { dateFormat } from '@/utils/funcs';
import EasyGroupModal, { ExsyGroupModalMethods } from 'components/Mahjong/easyGroupModal';
import useGetData from 'hooks/useGetData';
import { connect } from 'react-redux';

export default connect((state: any) => state.global)(function ({ userInfo }) {
	const { filterInfo, page, viewInfo, setFilterInfo, setPageIndex, setViewInfo }: any = useGetData(
		getCardsList,
		{
			name: '',
			group_id: 0,
		},
		'list'
	);
	const previewRef = useRef<ExsyGroupModalMethods>();
	const [options, setoptions] = useState([{ value: 0, label: '全部' }]);
	const navigate = useNavigate();
	const location: any = useLocation();
	useEffect(() => {
		if (location.state) {
			const { state } = location;
			setoptions([state]);
			setFilterInfo({ ...filterInfo, group_id: state.value });
		}
	}, []);
	const columns: any = [
		{ title: '编号', dataIndex: 'id', width: 60 },
		{ title: '名称', dataIndex: 'name', width: 160 },
		{ title: '创建时间', dataIndex: 'createtime', width: 160, render: (v: string) => dateFormat(v) },
		{
			title: '操作',
			// fixed: "right",
			width: 210,
			render: (e: any, { id, deck, name, u_id }: any, index: number) => (
				<div className=' gap-1 flex'>
					<Button
						key={'view-' + id}
						onClick={() => {
							if (!deck || !deck.length) return message.error('不包含任何牌！');
							previewRef.current!.preview({ deck });
						}}>
						预览
					</Button>
					{userInfo['u_id'] === u_id ? (
						<>
							<Button
								key={'edit-' + id}
								onClick={() => {
									navigate('../addcards', { state: { id, name } });
								}}>
								编辑
							</Button>
							<Popconfirm
								placement='topLeft'
								title='警告'
								description='删除牌型后，相关牌组也会受到影响！确认继续？'
								onConfirm={async () => {
									await delCards(id);
									const { list } = viewInfo;
									list.splice(index, 1);
									setViewInfo({ ...viewInfo, list: [...list] });
								}}
								okText='Yes'
								cancelText='No'
								key={'del-' + id}>
								<Button>删除</Button>
							</Popconfirm>
						</>
					) : (
						''
					)}
				</div>
			),
		},
		,
	];
	return (
		<div>
			<EasyGroupModal innerRef={previewRef} />
			<div className=' flex items-center mb-4'>
				<p>名称：</p>
				<Input
					style={{ width: 260 }}
					value={filterInfo.name}
					onChange={({ target: { value: name } }) => {
						setFilterInfo({ ...filterInfo, name }); // deep clone
					}}
					placeholder='关键词'
				/>
				<p className=' ml-4'>牌组：</p>
				<Select
					style={{ width: 260 }}
					showSearch
					value={filterInfo.group_id}
					allowClear={filterInfo.group_id}
					placeholder='输入牌组名称搜索'
					defaultActiveFirstOption={false}
					showArrow={false}
					filterOption={false}
					onClear={() => {
						setoptions([{ value: 0, label: '全部' }]);
						setFilterInfo({ ...filterInfo, group_id: 0 });
					}}
					onSearch={async (newValue: string) => {
						if (!newValue) return;
						const { list } = await getDeckList({ name: newValue });
						setoptions(list.map(({ id, name }: any) => ({ value: id, label: name })));
					}}
					onChange={(group_id) => {
						if (group_id) setFilterInfo({ ...filterInfo, group_id }); // deep clone
					}}
					notFoundContent={null}
					options={options}
				/>
				<Button
					className=' ml-auto mr-1'
					onClick={() => {
						navigate('../addcards');
					}}>
					新建牌型
				</Button>
			</div>
			<Table
				dataSource={viewInfo.list || []}
				columns={columns}
				scroll={{ y: 'initial' }}
				rowKey={({ id }) => `row-${id}`}
				pagination={{
					total: viewInfo.total,
					showTotal: (total) => `共 ${total} 项`,
					showSizeChanger: false,
					position: ['bottomLeft'],
					current: page,
					defaultPageSize: 15,
					onChange: (e) => setPageIndex(e),
				}}
			/>
		</div>
	);
});
